package com.fddh.springboot.controller;

import com.fddh.springboot.dto.LoginUserDto;
import com.fddh.springboot.dto.ResponseDto;
import com.fddh.springboot.dto.UserDto;
import com.fddh.springboot.enums.RoleEnum;
import com.fddh.springboot.enums.YesNoEnum;
import com.fddh.springboot.mapper.UserMapper;
import com.fddh.springboot.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

//@CrossOrigin解决前后端跨域问题
@CrossOrigin
@Controller
@RequestMapping(value="/user")
public class LoginController {

    @Autowired
    @Qualifier("LoginServiceImpl") //取得bean，指定bean名称为LoginServiceImpl
    private LoginService loginService;

    //查看用户角色这个小实现不再经过Service层，直接从Mapper层取到数据
    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员登录 /login
     */
    @ResponseBody
    @RequestMapping(value = "/login")   //监听login请求   //UserDto对应用户请求的数据类型
    public ResponseDto login(@RequestBody UserDto userDto, HttpServletRequest request) throws Exception {

        System.out.println("用户请求的body is:"+userDto);

        //LoginUserDto对应查询出来的user信息
        LoginUserDto loginUserDto = loginService.login(userDto);

        //ResponseDto对应返回给前端的数据
        ResponseDto responseDto = new ResponseDto();

        //设置登陆成功与否的标志
        if(loginUserDto!=null){
            //设置用户存在对应code是YES
            responseDto.setCode(YesNoEnum.YES);
        }
        else {
            //设置用户存在对应code是NO
            responseDto.setCode(YesNoEnum.NO);
        }

        //get a role from database
        int role = userMapper.getUserRole( userDto.getUsername() );//provide a user name from login to give mapper
        //当前登录用户是1:超级管理员,2:普通管理员
        if(role==1){
            responseDto.setRole(RoleEnum.Super);
        }else{
            responseDto.setRole(RoleEnum.Ordinary);
        }

        //返回数据responseDto给前端
        responseDto.setContent(loginUserDto);
        return responseDto;
    }

}
